﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GeoFences.aspx.cs" Inherits="GPSTrackingWebsiteManager.Pages.GeoFences" %>

<!DOCTYPE html>
<link href="../Css/GPSTrackingWebsite.css" rel="stylesheet" />
<script src="../Javascript/WindowMessageManager.js"></script>
<script src="../Javascript/ObjectsV2.js"></script>
<script src="../Javascript/GoogleMapManagerV2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false">  </script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Administrador de Geo Cercas</title>
</head>
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
    <script type="text/javascript">

        var opener = GetRadWindow();
        var GeoFences = new GeoFences();
        var Companies = new Companies();

        function GetRadWindow() {
            var oWindow = null;
            if (window.radWindow)
                oWindow = window.radWindow;
            else if (window.frameElement.radWindow)
                oWindow = window.frameElement.radWindow;
            return oWindow.BrowserWindow;
        }

        function getCompaniesByAdminUsername() {
            requestStart(getrpvGeoFencesUpdateControl());
            PageMethods.wsGetCompaniesByAdminUsername(getCompaniesByAdminUsernameOk, getCompaniesByAdminUsernameError);
        }

        function getCompaniesByAdminUsernameOk(object) {
            Companies.openXMLCompaniesByAdminUsername(object, opener.globalGeoFences.companiesList);
            Companies.loadCompaniesDataSource(getCompaniesGrid(), opener.globalGeoFences.companiesList, opener.globalGeoFences.companiesDataSource);
            if (opener.globalGeoFences.companiesList.length == 1) {
                getCompaniesGrid().selectItem(0);
                if (GeoFences.isValidToGetGeoFences(getGeoFenceGrid(), opener.globalGeoFences.companyID, opener.globalGeoFences.companiesList[0].companyID, opener.globalGeoFences.geoFencesList, opener.globalGeoFences.companiesList, opener.globalGeoFences.geoFencesDataSource)) {
                    //requestStart(getrpvClientManagerUpdateControl());
                    opener.globalGeoFences.companyID = opener.globalGeoFences.companiesList[0].companyID;
                    getGeoFencesByCompanyID();
                }
            }
            else {
                responseEnd(getrpvGeoFencesUpdateControl());
            }
        }

        function getCompaniesByAdminUsernameError(error) {
            responseEnd(getrpvGeoFencesUpdateControl());
            msgError(error.get_message(), titles.clientTitle);
        }

        function CompaniesGrid_OnRowClick(sender, args) {
            if (GeoFences.isValidToGetGeoFences(getGeoFenceGrid(), opener.globalGeoFences.companyID, args.getDataKeyValue("CompanyID"), opener.globalGeoFences.geoFencesList, opener.globalGeoFences.companiesList, opener.globalGeoFences.geoFencesDataSource)) {
                requestStart(getrpvGeoFencesUpdateControl());
                opener.globalGeoFences.companyID = args.getDataKeyValue("CompanyID");
                getGeoFencesByCompanyID();
            }
        }

        function enableDisableGeoFenceEventClickMap() {

            if (getCkbEnableDisableGeoFence().checked) {
                //getCkbCustomer().checked = false;
                opener.objMapControl.clearListenerClic();
                if (opener.globalClientManager.clientMarker != null) {
                    opener.objMapControl.setVisibleMarker(opener.globalClientManager.clientMarker, false);
                    opener.objMapControl.setPositionMarker(opener.globalClientManager.clientMarker, null);
                }
                opener.objMapControl.addListenerClic();
            }
            else {
                opener.objMapControl.clearListenerClic();
                opener.objMapControl.clearGeoFenceMarkers(false);
            }
        }

        function getGeoFencesByCompanyID(){
            //requestStart(getrpvGeoFencesUpdateControl());
            PageMethods.wsGetGeoFencesByCompanyID(opener.globalGeoFences.companyID, getGeoFencesByCompanyIDOk, getGeoFencesByCompanyIDError);
        }

        function getGeoFencesByCompanyIDOk(object) {
            
            GeoFences.openXMLGeoFenceDetails(opener, object, opener.globalGeoFences.geoFencesList);
            GeoFences.loadGeoFenceDataSource(opener.globalGeoFences.geoFencesDataSource, opener.globalGeoFences.geoFencesList, getGeoFenceGrid());
            //GeoFences.openXMLCompaniesByAdminUsername(object, opener.globalGeoFences.companiesList);
            //GeoFences.loadCompaniesDataSource(getCompaniesGrid(), opener.globalGeoFences.companiesList, opener.globalGeoFences.companiesDataSource);
            responseEnd(getrpvGeoFencesUpdateControl());
        }

        function getGeoFencesByCompanyIDError(error) {
            responseEnd(getrpvGeoFencesUpdateControl());
            msgError(error.get_message(), titles.clientTitle);
        }

        function GeoFenceGrid_OnRowClick(sender, args) {

            if (args._domEvent.target.cellIndex == 0) {// La columna 0 Representa la columna de eliminar
                var index = GeoFences.getIndexGeoFenceID(opener.globalGeoFences.geoFencesList, args.getDataKeyValue("GeoFenceID"));
                if (index != -1) {
                    if (confirm('¿Desea eliminar la Geo Cerca?')) {
                        opener.globalGeoFences.geoFenceIDSelected = args.getDataKeyValue("GeoFenceID");
                        deleteGeoFenceCompletely();
                    }
                }
            }
        }

        function deleteGeoFenceCompletely() {
            
            if (opener.globalGeoFences.geoFenceIDSelected != -1) {
                requestStart(getrpvGeoFencesUpdateControl());
                getGeoFenceGrid().clearSelectedItems();
                PageMethods.wsGeoFenceDelete(opener.globalGeoFences.companyID, opener.globalGeoFences.geoFenceIDSelected, deleteGeoFenceCompletelyOk, deleteGeoFenceCompletelyError);
            }
            else {
                msgValidation("Debe seleccionar un polígono para eliminarlo.", titles.polygonoTitle);
            }
        }

        function deleteGeoFenceCompletelyOk(object) {

            if (object) {
                for (i = 0; i < opener.globalGeoFences.geoFencesList.length; i++) {

                    if (opener.globalGeoFences.geoFenceIDSelected == opener.globalGeoFences.geoFencesList[i].geoFenceID) {
                        opener.globalGeoFences.geoFencesList[i].hideGeoFence(opener);
                        opener.globalGeoFences.geoFencesList.splice(i, 1);
                    }
                }

                opener.objMapControl.clearGeoFenceMarkers(true);

                GeoFences.loadGeoFenceDataSource(opener.globalGeoFences.geoFencesDataSource, opener.globalGeoFences.geoFencesList, getGeoFenceGrid());

                responseEnd(getrpvGeoFencesUpdateControl());
                msgInformation("Se eliminó correctamente el polígono.", titles.polygonoTitle);
            }
            else {
                msgError("No se eliminó correctamente el polígono.", titles.polygonoTitle);
            }
        }

        function deleteGeoFenceCompletelyError(error) {
            responseEnd(getrpvGeoFencesUpdateControl());
            msgError(error.get_message(), titles.polygonoTitle);
        }

        function GeoFenceGrid_RowDeselecting(sender, args) {

            opener.globalGeoFences.geoFenceIDSelected = args.getDataKeyValue("GeoFenceID");
            var index = GeoFences.getIndexGeoFenceID(opener.globalGeoFences.geoFencesList, opener.globalGeoFences.geoFenceIDSelected);
            if (index != -1) {
                opener.globalGeoFences.geoFencesList[index].checked = false;
            }

            opener.globalGeoFences.geoFencesList[index].hideGeoFence(opener);
        }

        //Show Geofence on row selecting
        function GeoFenceGrid_RowSelecting(sender, args) {

            var index = -1;
            try {
                if (args._domEvent.target.cellIndex != 0) {
                    opener.globalGeoFences.geoFenceIDSelected = args.getDataKeyValue("GeoFenceID");
                    index = GeoFences.getIndexGeoFenceID(opener.globalGeoFences.geoFencesList, opener.globalGeoFences.geoFenceIDSelected);
                    if (index != -1) {
                        opener.globalGeoFences.geoFencesList[index].checked = true;
                        opener.objMapControl.centerMap(opener.objMapControl.addPosition(opener.globalGeoFences.geoFencesList[index].latitudeList[0], opener.globalGeoFences.geoFencesList[index].longitudeList[0]));
                        opener.objMapControl.zoomMap(10);
                    }
                    //GeoFences.geoFence_ShowAllGeoFenceIDChecked(opener);
                    //this.geoFence_ShowAllGeoFenceIDChecked = function (opener) {

                        for (lk = 0; lk < opener.globalGeoFences.geoFencesList.length; lk++) {

                            if (opener.globalGeoFences.geoFencesList[lk].checked) {
                                //opener.globalGeoFences.geoFencesList[lk].showGeoFence(opener.objMapControl.map);
                                //opener.objMapControl.setPolygono(opener.globalGeoFences.geoFencesList[lk].polygono, opener.objMapControl.map);
                                //opener.objMapControl.clear(opener.globalGeoFences.geoFencesList[lk].polygono);
                                //opener.globalGeoFences.geoFencesList[lk].polygono = opener.objMapControl.show(opener.globalGeoFences.geoFencesList[lk].numPosList, opener.globalGeoFences.geoFencesList[lk].latitudeList, opener.globalGeoFences.geoFencesList[lk].longitudeList);
                                opener.globalGeoFences.geoFencesList[lk].showGeoFence(opener);
                            }
                            else {
                                //opener.objMapControl.clear(opener.globalGeoFences.geoFencesList[lk].polygono);//opener.globalGeoFences.geoFencesList[lk].hideGeoFence();
                                opener.globalGeoFences.geoFencesList[lk].hideGeoFence(opener);
                            }
                        }

                    //}
                }
                else {
                    index = GeoFences.getIndexGeoFenceID(opener.globalGeoFences.geoFencesList, args.getDataKeyValue("GeoFenceID"));
                    if (index != -1) {
                        args.set_cancel(true);
                    }
                }
            }
            catch (e) {
                null;
            }
        }

        function geoFenceInsert() {
            if (GeoFences.isValidToInsert(opener, getRtbPolygonName().value)) {
                requestStart(getrpvGeoFencesUpdateControl());
                //PageMethods.wsGeoFenceInsertComplete(opener.globalGeoFences.companyID, getRtbPolygonName().value, opener.globalGeoFences.latitudePolygonoList, opener.globalGeoFences.longitudePolygonoList, geoFenceInsertOk, geoFenceInsertError);
                PageMethods.wsGeoFenceInsert(opener.globalGeoFences.companyID, getRtbPolygonName().value, opener.globalGeoFences.latitudePolygonoList, opener.globalGeoFences.longitudePolygonoList, geoFenceInsertOk, geoFenceInsertError);
            }
           
        }

        function geoFenceInsertOk(geoFenceDetails) {
            if (geoFenceDetails == "-1") {
                responseEnd(getrpvGeoFencesUpdateControl());
                msgValidation("El nombre definido para el Polígono ya esta registrado para esta compañia, debe cambiar el nombre del Polígono.", titles.polygonoTitle);
            }
            else {
                getRtbPolygonName().value = "";
                GeoFences.openXMLGeoFenceDetailsByGeoFenceID(opener, geoFenceDetails, getGeoFenceGrid());
                GeoFences.selectLastItemByImei(opener, getGeoFenceGrid());
                responseEnd(getrpvGeoFencesUpdateControl());
                
                msgInformation("Se registró correctamente el polígono.", titles.polygonoTitle);
            }

        }
        
        function geoFenceInsertError(error) {
            responseEnd(getrpvGeoFencesUpdateControl());
            msgError(error.get_message(), titles.polygonoTitle);
        }


        function getCkbEnableDisableGeoFence() {
            return $get('<%= ckbEnableDisableGeoFence.ClientID %>');
        }

        function getRtbPolygonName() {
            return $get('<%= rtbPolygonName.ClientID %>');
        }

        function getCompaniesGrid() {
            try {
                return $find("<%= rgCompaniesGrid.ClientID %>").get_masterTableView();
                }
                catch (ex) {
                    setTimeout(getCompaniesGrid, 100);
                }
        }

        function getGeoFenceGrid() {
            try {
                return $find("<%= rgGeoFenceGrid.ClientID %>").get_masterTableView();
            }
            catch (ex) {
                setTimeout(getGeoFenceGrid, 100);
            }
        }

        function getrpvGeoFencesUpdateControl() {
            return "<%=  rpvGeoFences.ClientID %>";
        }

        function requestStart(object) {
            try {
                $find("<%= RadAjaxLoadingPanel1.ClientID%>").show(object);
                }
                catch (e) {
                    null;
                }
            }

            function responseEnd(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").hide(object);
                }
                catch (e) {
                    null;
                }
            }

    </script>
</telerik:RadScriptBlock>
<body onload="getCompaniesByAdminUsername()">
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server"  EnablePageMethods="true" EnablePartialRendering="true"></telerik:RadScriptManager>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
				<telerik:AjaxSetting AjaxControlID="AjaxControlID1">
					<UpdatedControls>
						<telerik:AjaxUpdatedControl ControlID="Loading" LoadingPanelID="RadAjaxLoadingPanel1" />
					</UpdatedControls>
				</telerik:AjaxSetting>
			</AjaxSettings>
        </telerik:RadAjaxManager>
        
        
        <telerik:RadTabStrip ID="rtsGeoFences" runat="server" SelectedIndex="0" MultiPageID="rmpGeoFences" Skin="Metro"></telerik:RadTabStrip>
        <telerik:RadMultiPage ID="rmpGeoFences" runat="server" SelectedIndex="0">
            <telerik:RadPageView ID="rpvGeoFences" runat="server">
				<table>
					<tr>
                        <td colspan="2">
                            <fieldset>
								<legend>Nueva Geocerca</legend>
								<table >
									<tr>
                                        <td>
                                            <asp:CheckBox ID="ckbEnableDisableGeoFence" runat="server" Text="Habilitar Marcadores" onclick="javascript:enableDisableGeoFenceEventClickMap()" />
                                            &nbsp;&nbsp;
                                        </td>
                                        <td>
                                            Nombre:&nbsp;&nbsp;<telerik:RadTextBox ID="rtbPolygonName" runat="server"> </telerik:RadTextBox>
                                        </td>
                                        <td>
                                            <input id="btnSaveGeoFence1" type="button" value="Guardar GeoCerca" onclick="geoFenceInsert();" />
                                        </td>
									</tr>
                                                                        
								</table>
							</fieldset>
                        </td>
                    </tr>
                    <tr>
                                                <td>
                  
				            <fieldset>
					            <legend>Compañias Registradas</legend>
					            <telerik:RadGrid ID="rgCompaniesGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgCompaniesGrid_NeedDataSource" Skin="Metro" Width="250px">
						            <ClientSettings>
							            <Selecting AllowRowSelect="True" />
							            <ClientEvents OnRowClick="CompaniesGrid_OnRowClick" />
							            <Scrolling AllowScroll="True" UseStaticHeaders="False" />
						            </ClientSettings>
						            <MasterTableView ClientDataKeyNames="CompanyID" NoMasterRecordsText="No hay compañias registradas">
							            <CommandItemSettings ExportToPdfText="Export to PDF" />
							            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							            </RowIndicatorColumn>
							            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							            </ExpandCollapseColumn>
							            <Columns>
								            <telerik:GridBoundColumn DataField="CompanyID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="CompanyID" Visible="false">
								            </telerik:GridBoundColumn>
								            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true">
								            </telerik:GridBoundColumn>
							            </Columns>
							            <EditFormSettings>
								            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								            </EditColumn>
							            </EditFormSettings>
						            </MasterTableView>
						            <FilterMenu EnableImageSprites="true">
						            </FilterMenu>
					            </telerik:RadGrid>
				            </fieldset>
			            </td>
						<td>
							<fieldset>
								<legend>Lista de Geocercas</legend>
								<telerik:RadGrid ID="rgGeoFenceGrid" runat="server" Height="100px" AllowMultiRowSelection="True" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Skin="Metro" Width="300px" OnNeedDataSource="rgGeoFenceGrid_NeedDataSource">
									<ClientSettings>
										<Selecting AllowRowSelect="True" />
										<ClientEvents OnRowSelecting="GeoFenceGrid_RowSelecting" OnRowDeselecting="GeoFenceGrid_RowDeselecting" OnRowClick="GeoFenceGrid_OnRowClick"/>
										<Scrolling AllowScroll="True" UseStaticHeaders="False"  />
									</ClientSettings>
									<MasterTableView ClientDataKeyNames="GeoFenceID" NoMasterRecordsText="No hay geocercas">
										<CommandItemSettings ExportToPdfText="Export to PDF" />
										<RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
										</RowIndicatorColumn>
										<ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
										</ExpandCollapseColumn>
										<Columns>
											<telerik:GridImageColumn ImageUrl="..\Template\Icons\16px\Delete.gif" UniqueName="DeleteColumn"></telerik:GridImageColumn>
											<telerik:GridBoundColumn DataField="GeoFenceID" FilterControlAltText="Filter Description column" HeaderText="GeoFenceID" UniqueName="GeoFenceID" Visible="false">
											</telerik:GridBoundColumn>
											<telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Name" UniqueName="Name">
											</telerik:GridBoundColumn>
                                                                    
											<telerik:GridClientSelectColumn UniqueName="chkShowGeoFence"  HeaderText="Mostrar">
											</telerik:GridClientSelectColumn>
                                                                        
										</Columns>
										<EditFormSettings>
											<EditColumn FilterControlAltText="Filter EditCommandColumn column">
											</EditColumn>
										</EditFormSettings>
									</MasterTableView>
									<FilterMenu EnableImageSprites="true">
									</FilterMenu>
								</telerik:RadGrid>
                                                                            
							</fieldset>

						</td>
					</tr>
				</table>
            </telerik:RadPageView>
        </telerik:RadMultiPage>

        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default"></telerik:RadAjaxLoadingPanel>
    </form>
</body>
</html>
